package com.itheima.web;


import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.itheima.entity.Result;
import com.itheima.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay")
@Api(tags = "微信支付接口")
public class PayController {

    @Reference
    private OrderService orderService;


    @GetMapping("/wxpay/{id}")
    @ApiOperation("微信支付")
    public Result wxPay(@PathVariable("id")String id){
      String payOrder = orderService.wxPay(id);
    return new Result(payOrder);
    }

    @RequestMapping("/notify")
    public Result payNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 1.接收请求参数（xml）
        ServletInputStream in = request.getInputStream();
        // 2.将xml转为java对象
        XmlMapper xmlMapper = new XmlMapper();
        Map param = xmlMapper.readValue(in, Map.class);
//        System.out.println("param = " + param);
        //修改支付状态
        orderService.updatePayStatus(param);
//        // 4.返回微信平台，接收成功..
//        HashMap<String, String> result = new HashMap<>();
//        result.put("return_code", "SUCCESS");
//        result.put("return_msg", "OK");
//        // 将map转为xml
//        String xml = xmlMapper.writeValueAsString(result);
//        response.setContentType("application/xml;charset=utf-8");
//        response.getWriter().write(xml);
        return null;
    }

    @GetMapping("/check/{id}")
    public Result payCheck(@PathVariable("id")String id){
       boolean b = orderService.selectPayStatusById(id);
       return new Result(b);
    }
}
